<template>
  <div :class="screenClass" style="margin-left: 16px">
    <table-container
      v-model:columns="columns"
      v-model:is-fullscreen="isFullscreen"
      :loading="isLoading"
      :all-columns="allColumns"
      @refresh="refresh"
    >
      <template #container-side>
        <a-space>
          <batch-import
            file-code="infra_personnelAndMaterials"
            :import-url="`/api/procurement/infra/user-material-config/import`"
            export-type="apiUrl"
            title="人员物料维护"
            btn-tititle="Excel导入"
            :before-open="beforeOpen"
            @finish="importData"
            @subtable-refresh="importData"
          ></batch-import>
          <a-button :disabled="!props.selectPersonalObj" @click="openModals">
            按物料添加
          </a-button>
          <a-button
            :disabled="!props.selectPersonalObj"
            @click="handleOpenModal"
          >
            按品类添加
          </a-button>
          <a-button
            :disabled="!props.selectPersonalObj"
            @click="handleOpenModa3"
          >
            按供应商添加
          </a-button>
          <a-button :disabled="!props.selectPersonalObj" @click="UpdateClick">
            更新规则
          </a-button>
          <a-button :disabled="!props.selectPersonalObj" @click="CopyingClick">
            批量复制给指定人
          </a-button>
        </a-space>
      </template>
      <a-table
        v-model:selectedKeys="selectData"
        :columns="columns"
        :row-selection="rowSelection"
        row-key="id"
        :data="renderData"
        :loading="isLoading"
        :scroll="{ x: 100 }"
        :pagination="pagination"
        @select="selectItem"
        @selection-change="handleSelectionChange"
        @page-change="pageChange"
        @page-size-change="pageSizeChange"
      >
        <template #secretLevel="{ record }">
          <secretLevelInfo
            :record="{
              secretLevel: record.secretLevel,
              secretLevelName: record.secretLevelName,
            }"
          />
        </template>
        <template #operate="{ record }">
          <a-space>
            <a-button type="text" @click="handleDelete(record, rowIndex)"
              >删除</a-button
            >
          </a-space>
        </template>
      </a-table>
    </table-container>
    <myModal
      v-if="showModal"
      :select-personal-obj="props.selectPersonalObj"
      @close="closeMaterial"
    ></myModal>
    <addModal
      v-if="showModal2"
      :select-personal-obj="props.selectPersonalObj"
      @close="handleClose"
    ></addModal>
    <supplemodal
      v-if="showModal3"
      :select-personal-obj="props.selectPersonalObj"
      @close="handleCloseSupplier"
    ></supplemodal>
    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
      <template #title> 请确认 </template>
      <div>您确定要删除当前所选的数据？</div>
    </a-modal>
    <a-modal v-model:visible="visible1" @ok="handleOk1" @cancel="handleCancel1">
      <template #title> 请确认更新 </template>
      <div><a-progress :percent="0.2" :style="{ width: '90%' }" /></div>
    </a-modal>
    <a-modal
      :visible="visible2"
      @ok="handleOk2"
      @cancel="() => (visible2 = false)"
    >
      <template #title> 请确认更新 </template>
      <personTree @personalClick="personalClick"></personTree>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import tableContainer from '@/common/components/table-container/index.vue';
  import { defineAsyncComponent, reactive, ref } from 'vue';
  import lodash from 'lodash';
  import useFullScreen from '@/common/hooks/fullScreen';
  import usePagination from '@/common/hooks/pagination';
  import { Message, Modal } from '@arco-design/web-vue';
  import useModal from '@/common/hooks/modal';
  import secretLevelInfo from '@/common/components/secret-level-info/index.vue';

  import batchImport from '@/common/components/batch-import/index.vue';
  import {
    deleteConfig,
    changRule,
    saveByUser,
    // importExcelToData,
    // downloadFile,
  } from '@/api/Basimanagementapi/personnel-matrial';
  // import requestFile from '@/utils/request/requestForFile';
  import personTree from './personTree.vue';

  const props = defineProps(['selectPersonalObj']);
  const myModal = defineAsyncComponent(
    () =>
      import('@/views/basic-configuration/personnel-matrial/persoaddmodal.vue')
  );
  const addModal = defineAsyncComponent(
    () => import('@/views/basic-configuration/personnel-matrial/addmodal.vue')
  );
  const supplemodal = defineAsyncComponent(
    () =>
      import('@/views/basic-configuration/personnel-matrial/suppliermodal.vue')
  );

  const emit = defineEmits([
    'handleWarehousing',
    'handleEdit',
    'handleCheck',
    'handleDetail',
    'refresh',
    'pageChange',
    'pageSizeChange',
  ]);
  const { isFullscreen, screenClass } = useFullScreen();
  const { pagination, setCurrent, setPageSize, setTotal, queryPagination } =
    usePagination();
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      width: 80,
    },
    {
      title: '密级',
      dataIndex: 'secretLevel',
      slotName: 'secretLevel',
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
    },
    {
      title: '物料类型',
      dataIndex: 'materialTypeName',
    },
    {
      title: '一级品类',
      dataIndex: 'categoryLv1',
    },
    {
      title: '二级品类',
      dataIndex: 'categoryLv2',
    },
    {
      title: '三级品类',
      dataIndex: 'categoryLv3',
    },
    {
      title: '物料状态',
      dataIndex: 'materialStatusName',
    },
    {
      title: '操作',
      dataIndex: '113',
      width: 80,
      slotName: 'operate',
      fixed: 'right',
    },
  ];
  const selectPersonal = ref();
  const selectDataList = ref([]);
  const { showModal, openModal, closeModal } = useModal();
  const personalClick = (val) => {
    selectPersonal.value = val;
  };
  const openModals = () => {
    openModal();
  };
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const selectData = ref([]);
  const showModal2 = ref(false);
  const handleOpenModal = () => {
    showModal2.value = true;
  };
  const closeMaterial = () => {
    closeModal();
    refresh();
  };
  const handleClose = () => {
    showModal2.value = false;
    refresh();
  };
  const showModal3 = ref(false);
  const handleOpenModa3 = () => {
    showModal3.value = true;
  };
  const handleCloseSupplier = () => {
    showModal3.value = false;
    refresh();
  };
  const allColumns = lodash.cloneDeep(columns);
  const renderData = ref<any[]>([]);
  const init = (val: any[], total: number) => {
    val.map((item: any, num: any) => {
      item.index = num + 1;
      return item;
    });
    renderData.value = val;
    isLoading.value = false;
    setTotal(total);
  };
  const refresh = () => {
    const page = {
      pageNo: 1,
      pageSize: 10,
    };
    emit('refresh', page);
  };
  const pageChange = (val: number) => {
    setCurrent(val);
    emit('pageChange', lodash.cloneDeep(queryPagination.value));
  };
  const pageSizeChange = (val: number) => {
    setPageSize(val);
    emit('pageSizeChange', lodash.cloneDeep(queryPagination.value));
  };
  const visible = ref(false);
  const visible1 = ref(false);
  const visible2 = ref(false);
  const handleDelete = (record) => {
    Modal.warning({
      title: '请确认',
      content: '您确定要删除所选的数据？',
      hideCancel: false,
      onOk: async () => {
        await deleteConfig(record.id || '');
        Message.success('删除成功');
        refresh();
      },
    });
  };
  const UpdateClick = () => {
    Modal.warning({
      title: '请确认',
      content: '您确定要更新规则',
      hideCancel: false,
      onOk: async () => {
        const { data } = await changRule({
          userId: props.selectPersonalObj.id,
          userCode: props.selectPersonalObj.userCode,
          userName: props.selectPersonalObj.username,
        });
        if (data) {
          Message.success('更新成功');
          refresh();
        } else {
          Message.warning('更新失败');
        }
      },
    });
    // visible1.value = true;
  };
  const CopyingClick = () => {
    if (selectData.value.length === 0) {
      Message.warning('请至少选择一条数据');
      return;
    }
    visible2.value = true;
  };
  const handleOk = () => {
    visible.value = false;
    Message.info({
      content: '删除成功！',
      duration: 5 * 1000,
    });
  };
  const handleCancel = () => {
    visible.value = false;
  };
  const handleOk1 = () => {
    visible.value = false;
    Message.info({
      content: '更新成功',
      duration: 5 * 1000,
    });
  };
  const handleCancel1 = () => {
    visible.value = false;
  };
  const selectItem = (itemList, item, itemObj) => {
    console.log(itemList, item, itemObj);
  };
  const handleSelectionChange = (itemList: any) => {
    selectDataList.value = itemList.map((item) => {
      return renderData.value.find((i) => i.id === item);
    });
  };
  const handleOk2 = async () => {
    if (!selectPersonal.value) {
      Message.warning('请选择人员进行操作');
      return;
    }
    const params = [];
    selectDataList.value.forEach((v) => {
      console.log(v, '000v');
      console.log(props.selectPersonalObj);
      if (v.addType === '按品类添加') {
        v.addTypes = '1';
      } else if (v.addType === '按供应商添加') {
        v.addTypes = '2';
      } else {
        v.addTypes = '3';
      }
      const obj = {
        secretLevel: v.secretLevel,
        materialId: v.materialId,
        categoryLv1Id: v.categoryLv1Id,
        categoryLv2Id: v.categoryLv2Id,
        categoryLv3Id: v.categoryLv3Id,
        supplierId: v.supplierId,
        addType: v.addTypes,
        materialCode: v.materialCode,
        materialName: v.materialName,
        materialType: v.materialType,
        userId: selectPersonal.value.id,
        userCode: selectPersonal.value.userCode,
        userName: selectPersonal.value.username,
      };
      params.push(obj);
    });
    const { data } = await saveByUser(params);
    if (data) {
      Message.success('操作成功');
      visible2.value = false;
      selectData.value = [];
      refresh();
    }
    console.log(data);
  };
  const isLoading = ref(false);
  // 导入数据
  const importData = async () => {
    refresh();
  };
  defineExpose({ init, isLoading });
</script>

<style lang="less" scoped>
  .arco-btn {
    margin-right: 16px;
  }

  .arco-btn-outline {
    color: #1e2228 !important;
    border-color: #d9dee7 !important;
  }

  .btn-class {
    color: #1e89ff;
    cursor: pointer;
  }
</style>
